//
//  HomeViewController.m
//  IconMaster
//
//  Created by mac on 2017/7/25.
//  Copyright © 2017年 yangweiwei. All rights reserved.
//

#import "HomeViewController.h"
#import <BHInfiniteScrollView.h>
#import "HomeTableViewCell.h"
#import "ThemeViewController.h"
#import "HomeHeaderView.h"
#import "GuideView.h"
#import "CustomerScrollerView.h"
@interface HomeViewController ()<BHInfiniteScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, HomeHeaderViewDelegate,HomeTableViewCellDelegate>{

    NSInteger IsInStory;
    NSDictionary *shareDict_;
    
}
@property (weak, nonatomic) IBOutlet UISearchBar *searchbar;
@property (weak, nonatomic) IBOutlet UIView *scrollView;
@property (nonatomic, strong) NSArray *scrollerImgArr;
@property (weak, nonatomic) IBOutlet UIButton *listbtn;
@property (weak, nonatomic) IBOutlet UIButton *btnNew;
 
@property (weak, nonatomic) IBOutlet UIButton *privateBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView0;
@property (weak, nonatomic) IBOutlet UIView *adView;

@property (nonatomic, strong) NSMutableArray *listMutArr;
@property (nonatomic, strong) NSMutableArray *listModelMutArr;
@property (nonatomic, strong) NSArray *bannerArr;
@property (nonatomic, strong) GuideView *guidView;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) UIScrollView *myScrollView;
@end

@implementation HomeViewController
- (NSMutableArray *)listMutArr{

    if (!_listMutArr) {
        _listMutArr = [NSMutableArray array];
    }
    return _listMutArr;
}
- (NSMutableArray *)listModelMutArr{

    if (!_listModelMutArr) {
        _listModelMutArr = [NSMutableArray array];
    }
    return _listModelMutArr;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 马上进入刷新状态

}
- (NSString *)app_Version{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];  
    CFShow((__bridge CFTypeRef)(infoDictionary));  
    // app名称  
    //        NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];  
    // app版本  
   return  [infoDictionary objectForKey:@"CFBundleShortVersionString"];  

}
- (void)viewDidLoad { 
    [super viewDidLoad];
    
       
//    NSLog(@"*****%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"once"]);
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"once"]) {
        
        [self setImageViewINNav];

    } else {
        
        self.navigationController.navigationBarHidden = YES;
        [self setGuidPageView];
  
    }
//    NSLog(@"*****====%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"once"]);
    [self setBarType];
    self.tableView0.delegate = self;
    self.tableView0.dataSource = self;
    
    [self checkIOSInStore:^(NSInteger isbool) {
        IsInStory = isbool;
    }];
    [self shareDictInfo:^(NSDictionary *shareDict) {
        shareDict_ = shareDict;
        [[NSUserDefaults standardUserDefaults] setObject:shareDict forKey:@"shareDict"];
    }];

    
    [self getBannerData];
//    self.page = 0;
//    [self setListDataWithURL:AlbumList];
//     [self.tableView0.mj_header beginRefreshing];
//    self.tableView0.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
////        self.page = 0;
//        [self setListDataWithURL:AlbumList];
//    }];
    [self setListDataWithURL:AlbumListnew];
    self.tableView0.mj_footer = [MJRefreshFooter footerWithRefreshingBlock:^{
        [self setListDataWithURL:AlbumListnew];
    }];
       
    [self initAdmob];
    
    [IconmasterHttp GreatNetWorkingRequestType:GreatRequestType_GET andurl:GetADID andparameters:nil andcomplete:^(id json, NSError *error) {
        if ([json[@"code"] integerValue] == 200) {
            if (![[NSString stringWithFormat:@"%@",json[@"data"][@"admobAd"]] isEqualToString:@"<null>"]) {
                [self writefile:json[@"data"][@"admobAd"] fileName:@"ADIDFiles.plist"];
            }
            
            //            dict(json[@"data"][@"admobAd"]);
        } 
        //        else {
        //            //
        //            dict([self readFiles]);
        //        }
    }];

 
  
}
- (void)setGuidPageView{

    self.myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight)];
    self.myScrollView.backgroundColor = [UIColor whiteColor];
    for (int i=0; i<3; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"guidePage_%d",i]];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(KWidth * i, 0, KWidth, KHeight)];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        // 在最后一页创建按钮
        if (i == 2) {
            // 必须设置用户交互 否则按键无法操作
            imageView.userInteractionEnabled = YES;
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(KWidth / 3, KHeight * 7 / 8, KWidth / 3, KHeight / 16);
             [button setTitle:NSLocalizedString(@"立即体验" ,nil) forState:UIControlStateNormal];
            [button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
//            button.backgroundColor = [UIColor redColor];
//            [button setImage:[UIImage imageNamed:@"立即体验-拷贝-3"] forState:UIControlStateNormal];
            // [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];/
             button.layer.borderWidth = 2;
            button.layer.cornerRadius = 5;
            button.clipsToBounds = YES;
            button.layer.borderColor = [UIColor greenColor].CGColor;
            [button addTarget:self action:@selector(go:) forControlEvents:UIControlEventTouchUpInside];
            [imageView addSubview:button];
//            button.sd_layout.bottomSpaceToView(self, 80).centerXIs(KWidth / 2).widthIs(100).heightIs(50);
            
        }
        imageView.image = image;
        [self.myScrollView addSubview:imageView];
    }
    self.myScrollView.bounces = NO;
    self.myScrollView.pagingEnabled = YES;
    self.myScrollView.showsHorizontalScrollIndicator = NO;
    self.myScrollView.showsVerticalScrollIndicator = NO;
    self.myScrollView.contentSize = CGSizeMake(KWidth * 3, KHeight);
    self.myScrollView.delegate = self;
    [self.view addSubview:self.myScrollView];

}
// 点击按钮保存数据并切换根视图控制器
- (void) go:(UIButton *)sender{
    // 切换根视图控制器
    [self.myScrollView removeFromSuperview];
     [self setImageViewINNav];
    self.navigationController.navigationBarHidden = NO;
    [[NSUserDefaults standardUserDefaults] setObject:@"once" forKey:@"once"];
}

- (void)setListDataWithURL:(NSString *)url {

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.listModelMutArr removeAllObjects];
 
   
    NSString *string = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    [IconmasterHttp GreatNetWorkingRequestType:GreatRequestType_GET andurl:url andparameters:@{@"page":IntToString((long)self.page++) , @"system":@"ios",@"currentAppVersion":string} andcomplete:^(id json, NSError *error) {
        
        if ([json[@"code"] integerValue] == 200) {
            //
//            NSArray *arr = json[@"data"][@"list"][@"content"];
           
            [self endRefresh];
//            if (1 == self.page) { // 说明是在重新请求数据.
//                self.listMutArr = nil;
//            }
            
            [self.listMutArr addObjectsFromArray:json[@"data"][@"list"][@"content"]];
            NSArray *arr = json[@"data"][@"list"][@"content"];
            for (int i = 0; i < arr.count; i++) {
                
                if ([arr[i][@"albunIsVisable"] integerValue]) {
                    HomeModel *homeModel = [[HomeModel alloc] initWithDict:[HomeModel setDictModel:arr[i]]];
                    [self.listModelMutArr addObject:homeModel];
                } 
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self updateView];
        }else{
        
            [self endRefresh];
            
        }
    }];
}
/**
 * 更新视图.
 */
- (void) updateView
{
    [self.tableView0 reloadData];
}
/**
 *  停止刷新
 */
-(void)endRefresh{
    [self.tableView0.mj_header endRefreshing];
    [self.tableView0.mj_footer endRefreshing];
}
- (void)getBannerData{
 
    
    NSString *string = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSLog(@"--------%@", string);
    [IconmasterHttp GreatNetWorkingRequestType:GreatRequestType_GET andurl:BannerList andparameters:@{@"system":@"ios",@"currentAppVersion":string} andcomplete:^(id json, NSError *error) {
        if ([json[@"code"] integerValue] == 200) {
            _bannerArr = json[@"data"][@"list"][@"content"];
            NSMutableArray *muarr = [NSMutableArray arrayWithArray:json[@"data"][@"list"][@"content"]];
            [muarr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                //
                NSDictionary *dict = obj;
                if ([dict[@"bannerIsVisable"] integerValue] != 1) {
                    [muarr removeObjectAtIndex:idx];
                }
            }];
 
            _bannerArr = muarr;
            [self.tableView0 reloadData];
        }
    }];
}
- (IBAction)listBtnAction:(id)sender {

}
- (IBAction)newBtnAction:(id)sender {

}
- (IBAction)privateBtnAction:(id)sender {
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.listModelMutArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 200*ScreenRatio_Heght;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    HomeTableViewCell *cell = [HomeTableViewCell cellWithTableView:self.tableView0];
    [cell dealWithHomeData:self.listModelMutArr[indexPath.row]];
    cell.delegate = self;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //
    [self addHot:self.listMutArr[indexPath.row][@"id"]];
  
     
        if (!IsInStory) {
            
            HomeModel *model = self.listModelMutArr[indexPath.row];
            if (model.IsLocked) {
                if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"IsLocked"] isEqualToString:@"IsLocked"]) {
                    [self shareAPP:model];                    
                    
                } else {
                    [self jumpToThemeViewController:self.listMutArr[indexPath.row][@"id"]];
                }

            } else {
                [self jumpToThemeViewController:self.listMutArr[indexPath.row][@"id"]];
            }
            
        }else{
            [self jumpToThemeViewController:self.listMutArr[indexPath.row][@"id"]];
             
        }
    
}


 
- (void)shareAPP:(HomeModel*)model{

    NSString *textToShare = NSLocalizedString(shareDict_[@"description"], nil) ; 
     
    
    
    UIImage *imageToShare = [UIImage imageNamed:@"icon"]; 
                        
    NSURL *urlToShare = [NSURL URLWithString:shareDict_[@"shareUrl"]];
      
//    NSLog(@"%@\n%@\n%@",shareDict_[@"thumb"],BaseURLImage,imageToShare);
    NSArray *activityItems = @[textToShare, imageToShare, urlToShare];
                        
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        //
        if (completed)  {   
            
            //                        NSLog(@"completed");
            [[NSUserDefaults standardUserDefaults] setObject:@"unlock" forKey:@"IsLocked"];
            model.IsLocked = NO;
            [self.tableView0 reloadData];
        }  
        
    };


}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return (736/2+ 50)*ScreenRatio_Heght;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    HomeHeaderView *headerView = [HomeHeaderView headerViewWithTAbleView:tableView];
    headerView.delegate = self;
    headerView.imageArray = _bannerArr;
    headerView.userInteractionEnabled = YES;
//    [headerView headerViewData:self.allOrdersContentArr[section]];
    return headerView;
}
- (void)clickButton:(NSInteger)tag{

    if (tag == 0) {
        //最新
        [self.listMutArr removeAllObjects];
        self.page = 0;
        [self setListDataWithURL:AlbumListnew];
       
    }else if (tag == 1) {
        //排行榜
        [self.listMutArr removeAllObjects];
        self.page = 0;
        [self setListDataWithURL:AlbumListhot];
    } else {
        //私人订制
        [self performSegueWithIdentifier:@"homepri" sender:self];
    }
}
- (void)clickImageView:(NSDictionary *)dict{

//    NSLog(@"dict = %@", dict);
    if ([dict[@"bannerIsVisable"] integerValue] != 0) {
        [self jumpToThemeViewController:dict[@"id"]];
    }
    
}
- (void)jumpToThemeViewController:(NSString *)stringID{

//    [MBProgressHUD hideHUDForView:self.view animated:YES];
    ThemeViewController *themeView = [[ThemeViewController alloc] init];
    themeView.themeID = stringID;
    [self.navigationController pushViewController:themeView animated:YES];
}
- (void)clickLockButton:(NSDictionary *)dict{

    NSLog(@"ddddd");
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 240*ScreenRatio_Heght;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    
    //    NSLog(@"向下滑了%f距离", scrollView.contentOffset.y);
}
- (void)initAdmob
{
    GADBannerView* bannerView =
    [AdAndHint showBannerViewInController:self view:self.view frame:CGRectZero];
    CGRect bannerFrame = bannerView.frame;
    bannerFrame.origin.x = 0;
    bannerFrame.origin.y = KHeight -10-bannerFrame.size.height;
    bannerView.frame = bannerFrame;
    [self.adView addSubview:bannerView];
    bannerView.sd_layout.topEqualToView(self.adView).leftEqualToView(self.adView).rightEqualToView(self.adView).bottomEqualToView(self.adView);
//    bannerView.autoresizingMask = segmentControl.autoresizingMask;
    
    [AdAndHint loadInterstitialIfNeed];
}

- (void)addHot:(NSString *)stringID{

    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        [IconmasterHttp GreatNetWorkingRequestType:GreatRequestType_GET andurl:AddHot andparameters:@{@"id":stringID} andcomplete:^(id json, NSError *error) {
            //
//            NSLog(@"%@", json);
        }];
    });
    
 
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
